<?php
/**
 * Description: 获取历史模考
 * User: devforma
 * Date: 15/4/8
 * Time: 10:35
 */

require __DIR__ . '/includes/utils.php';

class GetHistoryMokao implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;
        
        if (validateUser($queryArgs) !== 1)
            return genOutput(1000);

        $statusText = array('1' => 'done', '2' => 'undone', '0' => 'fresh');

        $sql = 'SELECT `id`, `publish_date` FROM `qb_paper_mokao` WHERE `publish_date`<=:date
        ORDER BY `publish_date` DESC LIMIT 0, 7';
        $history = $cmsdb->getResults($sql, array(':date' => date('Y-m-d')));

        $mokaoList = array();
        foreach ($history as $day) {
            $miniMockInfo = getMiniMockInfo($day->publish_date);
            $userRecord = getMiniMockUsers($day->id);

            if (isset($userRecord[$queryArgs['user_id']])) {
                $status = $userRecord[$queryArgs['user_id']]['status'];
                $exerciseId = $userRecord[$queryArgs['user_id']]['id'];
                $score = $userRecord[$queryArgs['user_id']]['evaluate'];
            } else {
                $status = 0;
                $exerciseId = 0;
                $score = 0.0;
            }

            //计算击败了多少
            if ($status == 1) {
                $rank = $miniMockInfo['rank'];
                $rankScore = intval($score);
                $total = $lower = 0;

                foreach ($rank as $score => $persons) {
                    $total += $persons;
                    if ($score < $rankScore) {
                        $lower += $persons;
                    }
                }
                $defeat = round($lower/$total, 2);
            } else {
                $defeat = 0.0;
            }

            $mokaoList[] = array(
                'id' => intval($day->id),
                'exercise_id' => intval($exerciseId),
                'name' => $miniMockInfo['name'],
                'date' => $day->publish_date,
                'persons_num' => intval($miniMockInfo['persons_num']),
                'defeat' => $defeat,
                'status' => $statusText[$status]
            );
        }

        return genOutput(1, array(
            'paper_list' => $mokaoList
        ));
    }

    /**
     * 获取排名信息
     * @param string $date 日期
     * @param float $score 待比较分数
     * @return float
     */
    private function getRank($date, $score) {

        //通过缓存获取模考信息
        $miniMockInfo = getMiniMockInfo($date);
        $rankScore = intval($score);

        //计算击败了多少
        $rank = $miniMockInfo['rank'];
        $total = $lower = 0;
        foreach ($rank as $score => $persons) {
            $total += $persons;
            if ($score < $rankScore) {
                $lower += $persons;
            }
        }

        return round($lower/$total, 2);
    }

}